﻿using CIS.Web.Common;
using System;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	public class BaseController : Controller
	{
		protected ICISPrincipal LoginUser
		{
			get
			{
				return User as ICISPrincipal;
			}
		}

		protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
		{
			string cultureName = null;

			// Attempt to read the culture cookie from Request
			HttpCookie cultureCookie = Request.Cookies["_culture"];
			if (cultureCookie != null)
				cultureName = cultureCookie.Value;
			else
				cultureName = Request.UserLanguages != null && Request.UserLanguages.Length > 0 ?
					Request.UserLanguages[0] :  // obtain it from HTTP header AcceptLanguages
					null;
			// Validate culture name
			cultureName = CultureHelper.GetImplementedCulture(cultureName); // This is safe

			switch (cultureName)
			{
				case "en-us":
					ViewBag.EasyUiLanguage = "easyui-lang-en.js";
					break;

				default:
					ViewBag.EasyUiLanguage = "easyui-lang-zh_CN.js";
					break;
			}

			// Modify current thread's cultures            
			Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
			Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

			return base.BeginExecuteCore(callback, state);
		}

		protected internal JsonCamelCaseResult JsonCamelCase(object data,
					JsonRequestBehavior behavior,
					bool forEasyuiFormSubmit = false)
		{
			var result = new JsonCamelCaseResult
			{
				Data = data,
				JsonRequestBehavior = behavior,
			};
			if (forEasyuiFormSubmit)
			{
				result.ContentType = "text/plain";
			}
			return result;
		}
	}
}